package com.feihong.txgw.ui.activity.user;

import android.Manifest;
import android.app.Activity;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.PowerManager;
import android.support.annotation.NonNull;
import android.support.v7.app.AlertDialog;
import android.text.TextUtils;
import android.widget.TextView;
import android.widget.Toast;

import com.feihong.txgw.R;
import com.feihong.txgw.message.LoginMessage;
import com.feihong.txgw.model.base_bean.BaseResponse;
import com.feihong.txgw.ui.activity.base.BaseActivity;
import com.feihong.txgw.utils.ToastUtils;
import com.feihong.txgw.utils.helper.RxHelper;
import com.feihong.txgw.utils.manage.RetrofitManager;
import com.feihong.txgw.view.StatusView;

import java.util.ArrayList;

import butterknife.BindView;
import cn.pedant.SweetAlert.SweetAlertDialog;
import io.reactivex.Observer;
import io.reactivex.disposables.Disposable;
import me.dm7.barcodescanner.zbar.BarcodeFormat;
import me.dm7.barcodescanner.zbar.Result;
import me.dm7.barcodescanner.zbar.ZBarScannerView;
import permissions.dispatcher.NeedsPermission;
import permissions.dispatcher.OnNeverAskAgain;
import permissions.dispatcher.OnPermissionDenied;
import permissions.dispatcher.OnShowRationale;
import permissions.dispatcher.PermissionRequest;
import permissions.dispatcher.RuntimePermissions;

/**
 * Created by Sabirjan on 2017/6/29.
 * TXGWApp.
 * @class describe:邀请好友
 * 飞宏电子
 */
@RuntimePermissions
public class SannerActivity extends BaseActivity implements ZBarScannerView.ResultHandler {
    @BindView(R.id.mZXingScannerView) ZBarScannerView mScannerView;
    @BindView(R.id.scanner_txt_pagetitle) TextView mTitleTv;
    @BindView(R.id.scanner_status_layout) StatusView mStatusView;
    private boolean isNeeds = true;
    /**
     * 保持长亮
     */
    PowerManager powerManager = null;
    PowerManager.WakeLock wakeLock = null;

    private Disposable requestDisposable;

    @Override
    public void setTheme() {
        //保持长亮
        isDrakFont = false;
        powerManager = (PowerManager) this.getSystemService(Activity.POWER_SERVICE);
        wakeLock = this.powerManager.newWakeLock(PowerManager.FULL_WAKE_LOCK, "My Lock");
    }

    @Override
    public int setLayoutID() {
        return R.layout.activity_scanner;
    }

    @Override
    public void initView(Bundle savedInstanceState) {
        mTitleTv.setText("扫描用户二维码");
        setSpecificTitleLayout(mStatusView);
        ArrayList<BarcodeFormat> list = new ArrayList<>();
        //二维码
        list.add(BarcodeFormat.QRCODE);
        mScannerView.setFormats(list);
        SannerActivityPermissionsDispatcher.onNeedsPermissionWithCheck(this);
    }

    @Override
    public void onResume() {
        super.onResume();

        //保持长亮
        wakeLock.acquire();

        if (mScannerView != null && isNeeds) {
            mScannerView.resumeCameraPreview(SannerActivity.this);
        }


    }

    private void openCamera() {
        if (isNeeds) {
            new Handler().postDelayed(new Runnable() {
                @Override
                public void run() {
                    // Register ourselves as a handler for scan results.
                    mScannerView.setResultHandler(SannerActivity.this);
                    try {
                        mScannerView.startCamera();
                        // Start camera on resume

                    } catch (Exception ex) {
                        ex.printStackTrace();
                        showDialog("权限不足", "您没有开启次应用的使用摄像头权限。请到系统设置-->权限管理 开启摄像使用权限。如果您的手机上安装了第三方管家应用（360管家，腾讯管家等），请开启一下摄像头权限！", new DialogInterface.OnDismissListener() {
                            @Override
                            public void onDismiss(DialogInterface dialog) {
                                finish();
                            }
                        });
                    }
                }
            }, 200);
        } else {
            showDialog("权限不足", "您没有开启次应用的使用摄像头权限。请到系统设置-->权限管理 开启摄像使用权限。如果您的手机上安装了第三方管家应用（360管家，腾讯管家等），请开启一下摄像头权限！", new DialogInterface.OnDismissListener() {
                @Override
                public void onDismiss(DialogInterface dialog) {
                    finish();
                }
            });
        }
    }

    @Override
    public void onPause() {
        super.onPause();
        mScannerView.stopCamera();           // Stop camera on pause
        //释放常亮
        wakeLock.release();
    }

    @Override
    public void bindData() {

    }

    @Override
    public void onUserLogin(LoginMessage loginMessage) {

    }

    @NeedsPermission(Manifest.permission.CAMERA)
    void onNeedsPermission() {

        isNeeds = true;
        openCamera();
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        SannerActivityPermissionsDispatcher.onRequestPermissionsResult(this, requestCode, grantResults);
    }

    @OnPermissionDenied(Manifest.permission.CAMERA)
    void onPermissionDenied() {
        isNeeds = false;
        showDialog("权限不足", "您没有开启次应用的使用摄像头权限。请到系统设置-->权限管理 开启摄像使用权限。如果您的手机上安装了第三方管家应用（360管家，腾讯管家等），请开启一下摄像头权限！", new DialogInterface.OnDismissListener() {
            @Override
            public void onDismiss(DialogInterface dialog) {
                finish();
            }
        });
    }

    @OnNeverAskAgain(Manifest.permission.CAMERA)
    void onNeverAskAgain() {
        isNeeds = false;
        showDialog("权限不足", "您没有开启次应用的使用摄像头权限。请到系统设置-->权限管理 开启摄像使用权限。如果您的手机上安装了第三方管家应用（360管家，腾讯管家等），请开启一下摄像头权限！", new DialogInterface.OnDismissListener() {
            @Override
            public void onDismiss(DialogInterface dialog) {
                finish();
            }
        });
    }

    //扫码返回结果
    @Override
    public void handleResult(final Result result) {

        // Do something with the result here
        if (result.getOpenState() == -1) {
            showDialog("权限不足", "您没有开启次应用的使用摄像头权限。请到系统设置-->权限管理 开启摄像使用权限。如果您的手机上安装了第三方管家应用（360管家，腾讯管家等），请开启一下摄像头权限！", new DialogInterface.OnDismissListener() {
                @Override
                public void onDismiss(DialogInterface dialog) {
                    finish();
                }
            });
            return;
        }
        String content = result.getContents();
        // If you would like to resume scanning, call this method below:
        if (TextUtils.isEmpty(content)) {
            return;
        }
        if (content.startsWith("https://app.tongxungw.com")) {
            if (!isUserLogin()) {
                showConfirmDialog("未登录", "您还未登录，请先登录！", "登录", "取消",
                        new SweetAlertDialog.OnSweetClickListener() {
                            @Override
                            public void onClick(SweetAlertDialog sweetAlertDialog) {
                                sweetAlertDialog.dismiss();
                                Intent loginIntent = new Intent();
                                loginIntent.setClass(getActivity(), LoginActivity.class);
                                startActivity(loginIntent);
                                finish();
                            }
                        }, new SweetAlertDialog.OnSweetClickListener() {
                            @Override
                            public void onClick(SweetAlertDialog sweetAlertDialog) {
                                finish();
                            }
                        });
                return;
            }

            showProgressDialog("正在提交...");
            RetrofitManager.getInstance().inviteFriedns(content)
                    .compose(RxHelper.<BaseResponse>rxSchedulerHelper())
                    .subscribe(new Observer<BaseResponse>() {
                        @Override
                        public void onSubscribe(Disposable d) {
                            if(requestDisposable != null && !requestDisposable.isDisposed()){
                                requestDisposable.dispose();
                            }
                            requestDisposable = d;
                        }

                        @Override
                        public void onNext(BaseResponse baseResponse) {
                            if(activityIsDestory()){
                                return;
                            }
                            dismissProgressDialog();
                            if (baseResponse != null && baseResponse.code == 200) {
                                ToastUtils.getInstance().showLongToast("邀请成功！");
//                            finish();
                            } else if (baseResponse != null) {
                                ToastUtils.getInstance().showLongToast(baseResponse.msg);
                            }
                        }

                        @Override
                        public void onError(Throwable e) {

                            mScannerView.resumeCameraPreview(SannerActivity.this);
                            showDialog(null,getString(R.string.connect_service_error));
                            dismissProgressDialog();
                        }

                        @Override
                        public void onComplete() {

                        }
                    });
        } else {
            Toast.makeText(SannerActivity.this,"请扫描通讯100提供的邀请码",Toast.LENGTH_SHORT).show();
            new Handler().postDelayed(new Runnable() {
                @Override
                public void run() {
                    mScannerView.resumeCameraPreview(SannerActivity.this);
                }
            }, 500);
        }

    }

    @OnShowRationale(Manifest.permission.CAMERA)
    public void rationaleForCamera(final PermissionRequest request) {
        new AlertDialog.Builder(this)
                .setPositiveButton("允许", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(@NonNull DialogInterface dialog, int which) {
                        request.proceed();
                    }
                })
                .setNegativeButton("拒绝", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(@NonNull DialogInterface dialog, int which) {
                        request.cancel();
                    }
                })
                .setCancelable(false)
                .setMessage("请允许获取相机权限")
                .show();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if(requestDisposable != null && !requestDisposable.isDisposed()){
            requestDisposable.dispose();
        }
    }
}
